package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.config.KafkaConfiguration;
import com.example.demo.entity.Message;
import com.example.demo.service.KafkaService;
import com.example.demo.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/kafka")
public class KafkaController {
    @Autowired
    private KafkaService kafkaService;

    @Autowired
    private KafkaConfiguration kafkaConfiguration;

    /**
     * 发送文本消息
     * @param msg
     * @return
     */
    @GetMapping("/send/{msg}")
    public String send(@PathVariable String msg) {
        kafkaService.send(kafkaConfiguration.getMyTopic1(), msg);
        return "生产者发送消息给topic1："+msg;
    }

    /**
     * 发送JSON数据
     * @return
     */
    @GetMapping("/send2")
    public String send2() {
        Message message = new Message();
        message.setId(System.currentTimeMillis());
        message.setMsg("生产者发送消息到topic1: " + UUID.getUUID32());
        message.setSendTime(new Date());

        String value = JSON.toJSONString(message);
        log.info("生产者发送消息到topic1 message = {}", value);

        kafkaService.send(kafkaConfiguration.getMyTopic1(),value);
        return value;
    }

    /**
     * 发送JSON数据
     * @return
     */
    @GetMapping("/send3")
    public String send3() {
        Message message = new Message();
        message.setId(System.currentTimeMillis());
        message.setMsg("生产者发送消息到topic2: " + UUID.getUUID32());
        message.setSendTime(new Date());

        String value = JSON.toJSONString(message);
        log.info("生产者发送消息到topic2 message = {}", value);

        kafkaService.send(kafkaConfiguration.getMyTopic2(),value);
        return value;
    }

}
